package com.me.learnspring.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.me.learnspring.model.Drink;
import com.me.learnspring.model.Goods;
import com.me.learnspring.service.DrinkService;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class CartController {
	@Autowired
	private HttpSession session;
	
	@Autowired
	private DrinkService drinkService;
	
	private ObjectMapper mapper = new ObjectMapper();
	
	@GetMapping("")
	public String cart(Model model) {
		model.addAttribute("cart", session.getAttribute("cart"));
		return "/cart";
	}
	
	@PostMapping("")
	@ResponseBody
	public String buy(String id, Model model) throws JsonProcessingException {
		var cart = (Map<Long, Goods>) session.getAttribute("cart");
		if (cart == null) {
			cart = new HashMap<Long, Goods>();
			session.setAttribute("cart", cart);
		}
		Drink drink = drinkService.findById(id);
		if (drink != null) {
			if (cart.containsKey(drink.getId())) {
				cart.get(drink.getId()).increase();
			} else {
				cart.put(drink.getId(), new Goods(1, drink));
			}
		}
		model.addAttribute("cart", cart);
		var map = new HashMap<String, Object>();
		map.put("success", true);
		map.put("drink", drink.getName());
		return mapper.writeValueAsString(map);
	}
	
	@PostMapping("/reduce")
	@ResponseBody
	public Object reduce(Long id) {
		var cart = (Map<Long, Goods>) session.getAttribute("cart");
		var map = new HashMap<String, Object>();
		map.put("success", false);
		if (cart == null) {
			return map;
		}
		Goods drinkGoods = cart.get(id);
		if (drinkGoods.decrease()) {
			map.put("drink", drinkGoods.getGoods());
			map.put("success", true);
		}
		return map;
	}
	
	@PostMapping("/increase")
	@ResponseBody
	public Object increase(Long id) {
		var cart = (Map<Long, Goods>) session.getAttribute("cart");
		var map = new HashMap<String, Object>();
		map.put("success", false);
		if (cart == null) {
			return map;
		}
		Goods drinkGoods = cart.get(id);
		drinkGoods.increase();
		map.put("drink", drinkGoods.getGoods());
		map.put("success", true);
		return map;
	}
	
	@PostMapping("/cancle")
	@ResponseBody
	public Object cancle(Long id) {
		var cart = (Map<Long, Goods>) session.getAttribute("cart");
		var map = new HashMap<String, Object>();
		map.put("success", false);
		if (cart == null) {
			return map;
		}
		Goods drinkGoods = cart.remove(id);
		map.put("drink", drinkGoods.getGoods());
		map.put("success", true);
		return map;
	}
}
